package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import com.hmdp.utils.RedisConstants;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_CODE_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private static final String KEY_PREFIX = "login:code:";
    private static final String KEY_PREFIX_TOKEN = "login:token:";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone); //
        if (!phoneInvalid) { // 手机号格式错误
            return Result.fail("手机号格式错误");
        }
        //2.生成验证码
        //TODO:随机生成一个6为数
        log.info("开始生成验证码");
        String code = RandomUtil.randomNumbers(6);
        //3.保存验证码到session中
        //TODO:3.优化将验证码保存到Redis中,key：手机号，value:验证码，设置过期时间为，防止验证码被重复使用
//        session.setAttribute("code", code);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, 1, TimeUnit.MINUTES);

        //4.发送验证码到手机上
        System.out.println("验证码：" + code);
        log.debug("发送验证码成功，验证码：{}", code);
        //5.返回结果
        return Result.ok(code);
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(loginForm.getPhone());
        if (!phoneInvalid) {
            log.info("判段手机号");
            return Result.fail("手机号格式错误");
        }
        //2.校验验证码：
        //TODO:2.优化从Redis中获取验证码
//        String cacheCode = (String) session.getAttribute("code");
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());
        String code = loginForm.getCode(); //用户填写的验证码
        if (!code.equals(cacheCode)|| cacheCode == null) {
            log.info("判段验证码");
            return Result.fail("验证码错误");
        }

        //3.根据手机号查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, loginForm.getPhone());
        User user = this.getOne(queryWrapper);
        if (user == null) {
            log.info("判段数据库中是否包含用户");
            user = createUserWithPhone(loginForm.getPhone());
        }


        //4.保存用户信息到session中
        //TODO:4.优化将用户信息保存到Redis中，key：手机号，value:用户信息，设置过期时间为，防止用户信息被重复使用
        //      key:token，value:用户信息
        //4.1生成 token
        String token = UUID.randomUUID().toString();
        //4.2将对象转化为Hash
        //拷贝
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将对象转化为map
//        Map<String, Object> map = BeanUtil.beanToMap(userDTO);
        Map<String, Object> map = BeanUtil.beanToMap(userDTO,
                new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true) //忽略null值
                        .setFieldValueEditor((fieldName,fieldValue) ->
                            fieldValue.toString()));//设置字段值编辑器
        //4.3将map保存到Redis中
//        session.setAttribute("user", user);
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+ token, map);
        log.info("用户登录成功，用户信息：{}", userDTO);
        //设置过期时间
        stringRedisTemplate.expire(LOGIN_USER_KEY+ token, 30, TimeUnit.MINUTES );//30分钟
        //5.返回结果
        return Result.ok(token);
    }

    @Override
    public Result queryUserById(Long userId) {
        //查询详情
        User user = this.getById(userId);
        if (user == null){
            return Result.fail("用户不存在");
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //返回
        return Result.ok(userDTO);
    }

    // 新增用户创建方法
    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName("用户_" + RandomUtil.randomString(8));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        this.save(user);
        return user;
    }
}
